package com.leet.code.thread;

public class Code1114 {

    public static void main(String[] args) throws InterruptedException {
        Foo foo = new Foo();

        Runnable r1 = () -> {
            System.out.println("first");
        };
        Runnable r2 = () -> {
            System.out.println("second");
        };
        Runnable r3 = () -> {
            System.out.println("third");
        };

        foo.first(r1);
        foo.second(r2);
        foo.third(r3);
    }


    static class Foo {

        int i;

        public Foo() {
            i = 0;
        }

        public synchronized void first(Runnable printFirst) throws InterruptedException {
            printFirst.run();
            i = 1;
            this.notify();
        }

        public synchronized void second(Runnable printSecond) throws InterruptedException {
            while (i != 1) {
                this.notify();
                this.wait();
            }
            printSecond.run();
            i = 2;
            this.notify();
        }

        public synchronized void third(Runnable printThird) throws InterruptedException {
            while (i != 2) {
                this.notify();
                this.wait();
            }
            // printThird.run() outputs "third". Do not change or remove this line.
            printThird.run();
        }
    }

}
